package com.lq.file.filemanager;

import com.lq.file.filemanager.entity.FtpFileServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.io.IOException;
import java.net.SocketException;

@SpringBootApplication
@Slf4j
public class FileManagerApplication {
    public static void main(String[] args) {
        SpringApplication.run(FileManagerApplication.class, args);
    }
        @Autowired
        private FtpFileServer fileServer;
    @Bean
    public FTPClient ftpClient() {
        FTPClient ftpClient = new FTPClient();
        //设置连接超时时间
        ftpClient.setConnectTimeout(fileServer.getFileServerConnectTimeOut());
        //设置ftp字符集
        ftpClient.setControlEncoding(fileServer.getFileServerControlEncoding());
        //设置被动模式，文件传输端口设置
        // ftpClient.enterLocalPassiveMode();
        try {
            //设置文件传输模式为二进制，可以保证传输的内容不会被改变
            // ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            // ftpClient.connect(beansEntity.getIp()+":"+beansEntity.getPort());
            ftpClient.setDefaultPort(fileServer.getFileServerPort());
            ftpClient.connect(fileServer.getFileServerHost(), fileServer.getFileServerPort());
            ftpClient.login(fileServer.getUsername(), fileServer.getPassword());
            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                ftpClient.disconnect();
                log.info("未连接到FTP，用户名或密码错误!");
                return null;
            } else {
                log.info("FTP连接成功!");
                return ftpClient;
            }
        } catch (SocketException socketException) {
            log.error("FTP的IP地址可能错误，请正确配置!");
            return null;
        } catch (IOException ioException) {
            ioException.printStackTrace();
            log.error("FTP的端口错误,请正确配置!");
            return null;
        }
    }

}
